import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import userApi from '@/api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  // 登录
  const login = async (loginForm) => {
    try {
      const response = await userApi.login(loginForm)
      if (response.code === 200) {
        setToken(response.data.token)
        ElMessage.success(response.message || '登录成功')
        // 登录成功后获取用户信息
        await getCurrentUser()
        return true
      } else {
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  // 注册
  const register = async (registerForm) => {
    try {
      const response = await userApi.register(registerForm)
      if (response.code === 200) {
        ElMessage.success(response.message || '注册成功')
        return true
      } else {
        ElMessage.error(response.message || '注册失败')
        return false
      }
    } catch (error) {
      ElMessage.error(error.message || '注册失败')
      return false
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      const response = await userApi.getCurrentUser()
      if (response.code === 200) {
        setUserInfo(response.data)
        return response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能是token过期，清除登录状态
      logout()
    }
  }

  // 更新用户信息
  const updateUserInfo = async (updateData) => {
    try {
      const response = await userApi.updateCurrentUser(updateData)
      if (response.code === 200) {
        setUserInfo(response.data)
        ElMessage.success(response.message || '更新成功')
        return true
      } else {
        ElMessage.error(response.message || '更新失败')
        return false
      }
    } catch (error) {
      ElMessage.error(error.message || '更新失败')
      return false
    }
  }

  // 登出
  const logout = () => {
    setToken('')
    setUserInfo(null)
    ElMessage.success('已退出登录')
  }

  // 检查登录状态
  const checkAuth = async () => {
    if (token.value && !userInfo.value) {
      await getCurrentUser()
    }
  }

  return {
    // 状态
    token,
    userInfo,
    
    // 计算属性
    isLoggedIn,
    
    // 方法
    setToken,
    setUserInfo,
    login,
    register,
    getCurrentUser,
    updateUserInfo,
    logout,
    checkAuth
  }
}) 